package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;

import java.util.List;
import java.util.Map;

/**
 * @author Wang Chengzhi
 * @create 2019-10-24 9:00
 */
public class UserServiceImpl implements UserService {
    UserDao dao = new UserDaoImpl();
    @Override
    public List<User> findAllUser() {
        //1. 调用UserDao里面的查询方法
        List<User> list = dao.findAll();
        return list;
    }

    @Override
    public void addUser(User user) {
        //调用UserDao里面的插入方法
        dao.add(user);
    }

    @Override
    public void delUser(String id) {
        dao.delete(Integer.parseInt(id));
    }

    @Override
    public User selectUser(String id) {
        if (id != null && !"".equals(id)){

            User user = dao.select(Integer.parseInt(id));
            return user;
        }
        return null;
    }

    @Override
    public void updateUser(User user) {
        if (user != null ){
            dao.update(user);
        }
    }

    @Override
    public void delUsers(String[] ids) {
        if (ids != null && ids.length > 0){

            for (String id : ids) {
                delUser(id);
            }

        }
    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {

        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);

        if (currentPage <= 1){
            currentPage = 1;
        }

        //封装PageBean
        PageBean<User> pb = new PageBean<>();

        pb.setRows(rows);
        pb.setCurrentPage(currentPage);


        //调用dao方法查询总记录数
        int totalCount = dao.getTotalCount(condition);

        int totalPage = totalCount % rows == 0 ? totalCount / rows : totalCount / rows + 1;

        pb.setTotalCount(totalCount);
        pb.setTotalPage(totalPage);

        int start = (currentPage - 1) * rows;
        //分页查询
        List<User> list = dao.findByPage(start,rows,condition);

        pb.setList(list);

        return pb;
    }

    @Override
    public User findUserByUsernameAndPassword(User user) {

        if (user != null){
            User loginUser = dao.findUserByUsernameAndPassword(user);
            return loginUser;
        }

        return null;
    }


}
